<?php
/**
 * @author Eugenio Fage
 * http://eugeniofage.wordpress.com/
 * http://code.google.com/p/monky/
 * 
 */
class Category extends AppModel {
	var $name = 'Category';
	var $actsAs = array('Tree','Containable');
	var $validate = array(
		'name' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
	);
	//The Associations below have been created with all possible keys, those that are not needed can be removed

	var $hasMany = array(
		'Link' => array(
			'className' => 'Link',
			'foreignKey' => 'category_id',
			'dependent' => false,
		)
	);
	
	function getCats(){
		return $this->find('threaded',array(
			'fields'=>array('Category.id','Category.name','Category.parent_id'),
			'recursive'=>-1,
			'cacheKey'=>'cats'
		));
	}
	
	function getCategoryCoef($daysInterval=2){
		if(!$this->id) return;
		
		// @todo REFACTOR URGENTE, AHORA SE USA TREE BEHAVIOUR
		
		// if the coeff calculated has been calculated in the las 24 hours dont recalculate 
		if(time()-getUnixtime($this->field('modified'))< (60*60*24)) {
			return $this->field('calculated_coef');
		}
		
		
		$childrens=array_keys($this->find('list',array('conditions'=>array('Category.parent'=>$this->id))));
		$countChildrens=count($childrens);
		if(!$countChildrens)$countChildrens=1;
		
		$conditions=array('Link.status'=>'published');
		if(!empty($childrens)){
			$conditions['Link.category_id']=$childrens;
		}else {
			$conditions['Link.category_id']=$this->id;
		}
		
		if($daysInterval) $conditions[]='Link.status_modified > date_sub(now(), interval '.$daysInterval.' day)';
		
		$total_published=$this->Link->find('count',array('conditions'=>array('Link.type'=>'published'),'recursive'=>-1));
		
		$published=$this->Link->find('count',array(	'conditions'=>$conditions,'recursive'=>-1));
		
		$conditions['status']=array('published', 'queued');
		$publishedAndQueued=$this->Link->find('count',array('conditions'=>$conditions,'recursive'=>-1));
		
		if(!$publishedAndQueued){
			$publishedAndQueued=1;
		}
		if ($total_published == 0){
			$total_published = 1;
		}
				
		$coefficentPublished=$published/$publishedAndQueued;
		$coefficent = 0.7 * $coefficentPublished + 0.3 * $published / $total_published / $countChildrens ;
		$coefficent= $coefficent / $countChildrens;
		
		if($coefficentPublished==0){
			$coefficentPublished=1;
		}
		
		$coefficent = max(min($coefficent/$coefficentPublished, 1.5), 0.7);
	
		$prevCoefficent=$this->field('calculated_coef');
		if ($prevCoefficent  > 0.6 && $prevCoefficent  < 1.5) {
			$coefficent = 0.05 * $coefficent + 0.95 * $prevCoefficent;
		}
		
		
		$this->save(array('Category'=>array('calculated_coef'=> $coefficent)),false,array('calculated_coef'));
		return $coefficent;
	} 
	
	

}
?>